Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level order traversal of its nodes' values.
(ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[[3], [20,9], [15,7]]
题目大意:层次遍历,第一层从左到右,第二层从右到左,依次交换
题目难度:Medium
import java.util.*;
/**
* Created by gzdaijie on 16/6/7
*/
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if (root == null) return result;
queue.add(root);
boolean tag = true;
while (true) {
int size = queue.size();
if (size == 0) return result;
List<Integer> item = new LinkedList<>();
while (size-- > 0) {
TreeNode top = queue.poll();
if (tag) item.add(top.val);
else item.add(0, top.val);
if (top.left != null) queue.offer(top.left);
if (top.right != null) queue.offer(top.right);
}
result.add(item);
tag = !tag;
}
}
}